//
//  SimulationViewController.swift
//  BBLinkiOSProject
//
//  Created by liuzhu on 2018/12/3.
//  Copyright © 2018 liuzhu. All rights reserved.
//

import CoreLocation
import MapKit
import SVProgressHUD
import UIKit
class SimulationViewController: UIViewController {
    @IBOutlet var simBackView: UIView!
    @IBOutlet var debugTV: UITextView!
    @IBOutlet var distanceLabel: UILabel!
    @IBOutlet var timeLabel: UILabel!
    @IBOutlet var speedLabel: UILabel!
    @IBOutlet var goBT: UIButton!
    @IBOutlet var statusTitle: UILabel!
    @IBOutlet var mapView: MKMapView!
    var locationManager: CLLocationManager?
    var isSimulation: Bool = false
    var time: Int = 0
    var timer: Timer?
    var totalTime: Int = 0
    var totalDistance: Int = 0
    var lastTotalDistance: Int = 0
    var currentLat: Double?
    var currentLng: Double?
    var lastLat: Double?
    var lastLng: Double?
    lazy var panel: PanelView = {
        let pv = PanelView()
        pv.speedLabel.isHidden = true
        pv.progressLayer.strokeEnd = CGFloat(0 * 0.01)
        return pv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        UIApplication.shared.isIdleTimerDisabled = true // 页面常亮
        simBackView.layer.cornerRadius = 10
        simBackView.layer.masksToBounds = true
        goBT.layer.cornerRadius = 10
        goBT.layer.masksToBounds = true
        mapView.layer.cornerRadius = 10
        mapView.layer.masksToBounds = true
        mapView.alpha = 0.8
        mapView.isUserInteractionEnabled = false
        locationManager = CLLocationManager()
        locationManager!.requestWhenInUseAuthorization()
        statusTitle.text = "Ready to go"
        // 仪表
        panel.center = view.center
        let type = BBUtils.getPhoneType()
        if type == PhoneType.PHONE_MAX_XR{
            panel.center = CGPoint(x: 207.0, y: 448.0)
        }else if type == PhoneType.PHONE_X{
            panel.center = CGPoint(x: 187.5, y: 406.0)
        }else if type == PhoneType.PHONE_PLUS{
            panel.center = CGPoint(x: 207.0, y: 368.0)
        }
        view.addSubview(panel)

        simBackView.layer.shadowColor = UIColor(red: 83 / 255.0, green: 249 / 255.0, blue: 255 / 255.0, alpha: 1).cgColor
        simBackView.layer.shadowOpacity = 5.0
        simBackView.layer.shadowRadius = 10.0
        simBackView.layer.shadowOffset = CGSize(width: 0, height: 0)

        goBT.layer.shadowColor = UIColor(red: 83 / 255.0, green: 249 / 255.0, blue: 255 / 255.0, alpha: 1).cgColor
        goBT.layer.shadowOpacity = 5.0
        goBT.layer.shadowRadius = 3.0
        goBT.layer.shadowOffset = CGSize(width: 0, height: 0)
    }

    @IBAction func close(_ sender: Any) {
        releaseSomething()
        dismiss(animated: true, completion: nil)
    }

    @IBAction func goAction(_ sender: Any) {
        if isSimulation {
            if totalDistance < 100 {
                let con = UIAlertController(title: "Alert", message: "Data will not be synchronized to the cloud if the range is less than 100m", preferredStyle: UIAlertController.Style.alert)
                let acOk = UIAlertAction(title: "Stop cycling", style: UIAlertAction.Style.default) { _ in
                    self.releaseSomething()
                    self.dismiss(animated: true, completion: nil)
                    return
                }
                let acCancel = UIAlertAction(title: "Keep riding", style: UIAlertAction.Style.cancel) { _ in
                    return
                }
                con.addAction(acOk)
                con.addAction(acCancel)
                present(con, animated: true, completion: nil)
            } else {
                goBT.setTitle("Go", for: UIControl.State.normal)
                simBackView.layer.masksToBounds = true
                goBT.layer.masksToBounds = true
                statusTitle.text = "Ready to go"
                panel.speedLabel.isHidden = true
                uploadData()
                mapView.showsUserLocation = false
            }
        } else {
            if CLLocationManager.locationServicesEnabled() {
                simBackView.layer.masksToBounds = false
                goBT.layer.masksToBounds = false
                panel.speedLabel.isHidden = false
                mapView.mapType = MKMapType.standard
                mapView.showsUserLocation = true
                mapView.userTrackingMode = MKUserTrackingMode.followWithHeading
                goBT.setTitle("End", for: UIControl.State.normal)
                statusTitle.text = "Riding"
                timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timeAction), userInfo: nil, repeats: true)
            }
        }
        isSimulation = !isSimulation
    }

    @objc private func timeAction() {
        totalTime += 1
        timeLabel.text = "\(totalTime / 3600)H,\((totalTime % 3600) / 60)M,\(totalTime % 60)S"
        if totalTime > 5 {
            let speed = Double(totalDistance - lastTotalDistance) * 3.6 // 瞬时速度
            panel.speedLabel.text = String(format: "%.1lf", speed)
            UIView.animate(withDuration: 0.3) {
                self.panel.progressLayer.strokeEnd = CGFloat(speed * 0.01)
            }
            lastTotalDistance = totalDistance
        }
    }

    private lazy var locationStr: String = {
        var str = String()
        return str
    }()

    private func uploadData() {
        SVProgressHUD.show()
        let path = "day/save_activity.do"
        let params = ["token": BBUser.loadUser()?.token, "userId": BBUser.loadUser()?.userId, "dayId": getDayId(), "activityLines": locationStr, "deviceId": BBUser.loadUser()?.devices?.first?.deviceId, "distance": String(totalDistance), "usedTime": String(totalTime), "speedAvg": String(totalDistance / totalTime)]
        AFNetWorkManager.shareNetworkTools().post(path, parameters: params, progress: { _ in

        }, success: { _, _ in
            self.releaseSomething()
            SVProgressHUD.dismiss()
            SVProgressHUD.showSuccess(withStatus: "模拟成功，请到首页刷新查看")
            self.dismiss(animated: true, completion: nil)
        }) { _, error in
            SVProgressHUD.dismiss()
            self.releaseSomething()
            SVProgressHUD.showSuccess(withStatus: "模拟失败")
            self.dismiss(animated: true, completion: nil)
        }
    }

    private func getDayId() -> String {
        let now = Date()
        // 创建一个日期格式器
        let dformatter = DateFormatter()
        dformatter.dateFormat = "yyyy-MM-dd"
        return dformatter.string(from: now as Date)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        debugTV.resignFirstResponder()
    }

    // 计算经纬度之间的距离
    private func distanceBetweenOrderBy(lat1: Double, lat2: Double, lng1: Double, lng2: Double) -> Double {
        let curLocation = CLLocation(latitude: lat1, longitude: lng1)
        let lastLocation = CLLocation(latitude: lat2, longitude: lng2)
        let distance = curLocation.distance(from: lastLocation)
        return distance
    }

    deinit {
        print(#function)
        self.locationManager?.stopUpdatingLocation()
        mapView.showsUserLocation = false
        timer?.invalidate()
        timer = nil
    }

    private func releaseSomething() {
        locationManager?.stopUpdatingLocation()
        mapView.showsUserLocation = false
        timer?.invalidate()
        timer = nil
        UIApplication.shared.isIdleTimerDisabled = false // 页面常亮
    }
}

extension SimulationViewController: MKMapViewDelegate {
    // 当地图更新用户位置信息时调用
    // 蓝点: 大头针"视图"  大头针"数据模型"
    func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
        // MKUserLocation: 大头针数据模型
        // location : 者就是大头针的位置信息(经纬度)
        // heading: 设备朝向
        // title: 弹框标题
        // subtitle: 弹框子标题
        // 移动地图的中心,显示在当前用户所在的位置
        mapView.setCenter(userLocation.coordinate, animated: true)
        // 设置地图显示区域
        let center = (userLocation.coordinate)
        // let span = MKCoordinateSpan(latitudeDelta: 0.0219952102009202, longitudeDelta: 0.0160932558432023)
        let span = MKCoordinateSpan(latitudeDelta: 0.0005520879762741515, longitudeDelta: 0.0014495846340878416)
        let region: MKCoordinateRegion = MKCoordinateRegion(center: center, span: span)
        mapView.setRegion(region, animated: true)
    }

    // 区域改变的时候调用
    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        // print(mapView.region.span.latitudeDelta, mapView.region.span.longitudeDelta)
        if totalTime > 5 {
            print(mapView.region.center.longitude, mapView.region.center.latitude)
            lastLat = currentLat
            lastLng = currentLng
            currentLng = mapView.region.center.longitude
            currentLat = mapView.region.center.latitude
            if (currentLng != nil) && (currentLat != nil) && (lastLat != nil) && (lastLng != nil) {
                totalDistance += Int(distanceBetweenOrderBy(lat1: lastLat!, lat2: currentLat!, lng1: lastLng!, lng2: currentLng!))
                distanceLabel.text = "\(totalDistance / 1000).\((totalDistance % 1000) / 100)\((totalDistance % 100) / 10)km"
            }
            if totalTime % 5 == 0 { // 5秒记录一次经纬度
                if locationStr.count == 0 {
                    locationStr += String(format: "%.14lf:%.14lf", currentLng!, currentLat!)
                } else {
                    locationStr += String(format: ",%.14f:%.14f", currentLng!, currentLat!)
                }
            }
        }
    }
}
